package com.zhanghe.study.servlet.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        boolean hasCookie = false;
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("name")){
                hasCookie = true;
                System.out.println("包含cookie信息，name为"+cookie.getValue());
                // url编码，防止中文乱码
                String name = URLEncoder.encode(cookie.getValue(),"UTF-8");
                resp.sendRedirect("/webstudy/static/hello.html?name="+name);
            }
        }
        if(!hasCookie){
            resp.sendRedirect("/webstudy/static/login.html");
        }
    }
}
